package com.floreantpos.config.ui;

import javax.swing.JTextField;

import org.apache.commons.lang.StringUtils;

import net.miginfocom.swing.MigLayout;

import com.floreantpos.main.Application;
import com.floreantpos.model.Restaurant;
import com.floreantpos.model.dao.RestaurantDAO;
import com.floreantpos.swing.FixedLengthTextField;
import com.floreantpos.ui.dialog.POSMessageDialog;
import com.floreantpos.util.POSUtil;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.util.Locale;
import javax.swing.JCheckBox;

public class RestaurantConfigurationView extends ConfigurationView {

  private RestaurantDAO dao;
  private Restaurant restaurant;

  private JTextField tfRestaurantName = new FixedLengthTextField(40);
  private JTextField tfMsgEcf = new FixedLengthTextField(80);
  private JTextField tfAddressLine1 = new FixedLengthTextField(20);
  private JTextField tfAddressLine2 = new FixedLengthTextField(20);
  private JTextField tfAddressLine3 = new FixedLengthTextField(20);
  private JTextField tfTelephone = new FixedLengthTextField(16);
  private JTextField tfCurrencyName = new FixedLengthTextField(20);
  private JTextField tfCnpj = new FixedLengthTextField(32);
  private JTextField tfIe = new FixedLengthTextField(32);
  private JTextField tfCcm = new FixedLengthTextField(32);
  private JTextField tfCurrencySymbol = new FixedLengthTextField(10);
  private JTextField tfGratuityRate = new FixedLengthTextField(5);
  private JCheckBox chkSaveGuestsPerTable = new JCheckBox();
  private JCheckBox chkSaveGuestName = new JCheckBox();
  private JCheckBox chkAutoGenTicket = new JCheckBox();
  private JCheckBox chkSaveTaxId = new JCheckBox();

  private DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", new DecimalFormatSymbols(new Locale("pt", "BR")));

  public RestaurantConfigurationView() {
    setLayout(new MigLayout("align 50% 50%"));

    addRow(com.floreantpos.POSConstants.RESTAURANT_NAME_, tfRestaurantName, "w 300");
    addRow(com.floreantpos.POSConstants.ADDRESS_LINE1, tfAddressLine1, "w 300");
    addRow(com.floreantpos.POSConstants.ADDRESS_LINE2, tfAddressLine2, "w 300");
    addRow(com.floreantpos.POSConstants.ADDRESS_LINE3, tfAddressLine3, "w 300");
    addRow("Mensagem ECF:", tfMsgEcf, "w 300");
    addRow("CNPJ:", tfCnpj, "w 150");
    addRow("IE:", tfIe, "w 150");
    addRow("CCM:", tfCcm, "w 150");
    addRow(com.floreantpos.POSConstants.TELEPHONE + ":", tfTelephone, "w 150");
    addRow(com.floreantpos.POSConstants.CURRENCY_NAME_, tfCurrencyName, "w 50");
    addRow(com.floreantpos.POSConstants.CURRENCY_SYMBOL_, tfCurrencySymbol, "w 50");
    addRow("Percentual de Gratificação:", tfGratuityRate, "w 50");
    addCheckBox("Registrar Número de Clientes:", chkSaveGuestsPerTable);
    addCheckBox("Registrar Nome do Cliente:", chkSaveGuestName);
    addCheckBox("Número da Posição Automático:", chkAutoGenTicket);
    addCheckBox("Perguntar Documento do Cliente:", chkSaveTaxId);
  }

  @Override
  public boolean save() throws Exception {
    if (!isInitialized()) {
      return true;
    }

    String name = null;
    String msgEcf = null;
    String cnpj = null;
    String ie = null;
    String ccm = null;
    String addr1 = null;
    String addr2 = null;
    String addr3 = null;
    String telephone = null;
    String currencyName = null;
    String currencySymbol = null;

    int capacity = 0;
    int tables = 0;

    Double gratuityRate = Double.valueOf(0);

    Boolean saveGuestsPerTable = true;
    Boolean saveGuestName = true;
    Boolean autoGenTicket = true;
    Boolean saveTaxId = true;

    name = tfRestaurantName.getText();
    msgEcf = tfMsgEcf.getText();
    cnpj = tfCnpj.getText();
    ie = tfIe.getText();
    ccm = tfCcm.getText();
    addr1 = tfAddressLine1.getText();
    addr2 = tfAddressLine2.getText();
    addr3 = tfAddressLine3.getText();
    telephone = tfTelephone.getText();
    currencyName = tfCurrencyName.getText();
    currencySymbol = tfCurrencySymbol.getText();
    saveGuestsPerTable = chkSaveGuestsPerTable.isSelected();
    saveGuestName = chkSaveGuestName.isSelected();
    autoGenTicket = chkAutoGenTicket.isSelected();
    saveTaxId = chkSaveTaxId.isSelected();
    
    if(!StringUtils.isEmpty(cnpj)) {
      
      if(StringUtils.isEmpty(name)) {
        POSMessageDialog.showError(this, "Nome Inválido");
        return false;        
      }
      
      cnpj = POSUtil.checkTaxId(cnpj);
      
      if (cnpj.equals("*") || cnpj.length() < 18) {
        POSMessageDialog.showError(this, "CNPJ Inválido");
        return false;         
      }
      
    }
    
    if(!StringUtils.isEmpty(ie)) {
      if (!POSUtil.isNumeric(ie.replace(".", "").replace("/", "").replace("-", ""))) {
        POSMessageDialog.showError(this, "IE Inválida");
        return false; 
      }      
    }


    if(!StringUtils.isEmpty(ccm)) {
      if (!POSUtil.isNumeric(ccm.replace(".", "").replace("/", "").replace("-", ""))) {
        POSMessageDialog.showError(this, "CCM Inválido");
        return false; 
      }      
    }    
    
    if (StringUtils.isEmpty(currencyName)) {
      currencyName = com.floreantpos.POSConstants.DOLLAR;
    }
    if (StringUtils.isEmpty(currencySymbol)) {
      currencySymbol = "R$";
    }

    try {
      gratuityRate = Double.valueOf(decimalFormat.parse(tfGratuityRate.getText()).doubleValue());
    } catch (ParseException ex) {
      POSMessageDialog.showError(this, "Percentual de Gratificação Inválido");
      return false;
    }

    if (gratuityRate < 0) {
      POSMessageDialog.showError(this, "Percentual de Gratificação deve ser maior ou igual a 0");
      return false;
    }

    if (saveGuestsPerTable && saveGuestName) {
      POSMessageDialog.showError(this, "Para registrar o Nome do Cliente, desmarque a opção \"Registrar Número de Clientes\"");
      return false;
    }

    if (autoGenTicket && (saveGuestsPerTable || saveGuestName)) {
      POSMessageDialog.showError(this, "Para utilizar o Número da Posição Automático as opções:\n\"Registrar Número de Clientes\" e \"Registrar Nome do Cliente\",\ndevem estar desmarcadas.");
      return false;
    }
    
    if (!Application.isTestSystem() && !saveTaxId) {
      POSMessageDialog.showError(this, "A opção \"Perguntar Documento do Cliente\" é obrigatória.");
      return false;
    }

    restaurant.setName(name);
    restaurant.setAddressLine1(addr1);
    restaurant.setAddressLine2(addr2);
    restaurant.setAddressLine3(addr3);
    restaurant.setMsgEcf(msgEcf);
    restaurant.setCnpj(cnpj);
    restaurant.setIe(ie);
    restaurant.setCcm(ccm);
    restaurant.setTelephone(telephone);
    restaurant.setCapacity(capacity);
    restaurant.setTables(tables);
    restaurant.setCurrencyName(currencyName);
    restaurant.setCurrencySymbol(currencySymbol);
    restaurant.setGratuityRate(gratuityRate);
    restaurant.setSaveGuestsPerTable(saveGuestsPerTable);
    restaurant.setSaveGuestName(saveGuestName);
    restaurant.setAutoGenTicket(autoGenTicket);
    restaurant.setSaveTaxId(saveTaxId);

    dao.saveOrUpdate(restaurant);

    Application.getInstance().refreshRestaurant();

    return true;
  }

  @Override
  public void initialize() throws Exception {
    dao = new RestaurantDAO();
    restaurant = dao.get(Integer.valueOf(1));

    tfRestaurantName.setText(restaurant.getName());
    tfAddressLine1.setText(restaurant.getAddressLine1());
    tfAddressLine2.setText(restaurant.getAddressLine2());
    tfAddressLine3.setText(restaurant.getAddressLine3());
    tfCnpj.setText(restaurant.getCnpj());
    tfIe.setText(restaurant.getIe());
    tfCcm.setText(restaurant.getCcm());
    tfMsgEcf.setText(restaurant.getMsgEcf());
    tfTelephone.setText(restaurant.getTelephone());
    tfCurrencyName.setText(restaurant.getCurrencyName());
    tfCurrencySymbol.setText(restaurant.getCurrencySymbol());
    tfGratuityRate.setText(Application.formatNumber(restaurant.getGratuityRate()));
    chkSaveGuestsPerTable.setSelected(restaurant.isSaveGuestsPerTable());
    chkSaveGuestName.setSelected(restaurant.isSaveGuestName());
    chkAutoGenTicket.setSelected(restaurant.isAutoGenTicket());
    chkSaveTaxId.setSelected(restaurant.isSaveTaxId());

    setInitialized(true);
  }

  @Override
  public String getName() {
    return com.floreantpos.POSConstants.RESTAURANT_CONFIGURATION;
  }
}
